/**
 * Created by Administrator on 2016-03-21.
 */
var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    less = require('gulp-less'),
    notify = require('gulp-notify'),
    concat = require('gulp-concat'),
    minifycss = require('gulp-minify-css'),
    rename = require('gulp-rename'),
    connect = require('gulp-connect'),
    browserSync = require('browser-sync').create(),
    reload = browserSync.reload,
    sourcemaps = require("gulp-sourcemaps"),
    htmlImport = require('gulp-html-import'),
    runSequence = require('gulp-run-sequence'),
    px2rem = require('gulp-px2rem'),
    fileinclude = require('gulp-file-include'),
    gwatch = require('gulp-watch'),
    path = require('path'),
    fileSystem = require('fs'),
    changed = require('gulp-changed'),
    md5 = require("gulp-md5-plus"),
    clean = require('gulp-clean'),
    replace = require('gulp-replace'),
    plumber = require('gulp-plumber');




var ROOT = "./";
//ÁÙÊ±Ä¿Â¼
var tmpPath = {
    dist: ROOT + "dist",
    dev: ROOT + "src",
    cssDev: ROOT + "./src/css", //开发环境的css目录
    mid: ROOT + "mid", //中间目录
    build: ROOT + "dist",
};

var px2remOptions = {
    replace: true,
    rootValue: 100,
    minPx: 2
};

var postCssOptions = {
    map: true
};

gulp.task('less', function() {
    return gulp.src(tmpPath.cssDev + '/**/*.less')
        // `changed` 任务需要提前知道目标目录位置
        // 才能找出哪些文件是被修改过的
        .pipe(plumber())
        .pipe(changed(tmpPath.cssDev + '/**/*.less'))
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(autoprefixer('last 10 version'))
        .pipe(px2rem(px2remOptions))
        .pipe(concat("index.css")) //合并到一个文件
        .pipe(replace('../../images', '../images')) //替换合并后的路径，这个只能针对特定目录
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(tmpPath.mid + "/css"))
        .pipe(notify({
            message: "Generated file: <%= file.relative %>"
        }))
        .pipe(reload({ stream: true }));
});
//把html import到mid下
// gulp.task('import', function () {
//     gulp.src(tmpPath.dev+"/*.html")
//         .pipe(htmlImport(tmpPath.dev+"/component/"))
//         .pipe(gulp.dest(tmpPath.dev+"/mid")); 
// });

gulp.task('import', function() {
    gulp.src(tmpPath.dev + "/*.html")
        .pipe(changed(tmpPath.dev + "/component/"))
        .pipe(fileinclude({
            prefix: '@@',
            basepath: tmpPath.dev + "/component/"
        }))
        .pipe(gulp.dest(tmpPath.mid))
        .pipe(notify({
            message: "import html: <%= file.relative %>"
        }))
        .pipe(reload({ stream: true }));
});

//把服务器定在mid里面
gulp.task('browser', function() {
    browserSync.init({
        server: {
            baseDir: tmpPath.mid
        }
    });


    gulp.watch(tmpPath.mid + '/*.html').on('change', reload);
    gulp.watch(tmpPath.mid + '/+css/*').on('change', reload);
    gulp.watch(tmpPath.mid + '/images/*').on('change', reload);
    gulp.watch(tmpPath.mid + '/js/*.js').on('change', reload);

});


//开发环境*******************
gulp.task('js', function() {
    gulp.src(tmpPath.dev + '/js/**/*')
        .pipe(gulp.dest(tmpPath.mid + '/js'));
});
gulp.task('image', function() {
    gulp.src(tmpPath.dev + "/images/**/*")
        .pipe(gulp.dest(tmpPath.mid + "/images"));
});
gulp.task('json', function() {
    gulp.src(tmpPath.dev + "/json/**/*")
        .pipe(gulp.dest(tmpPath.mid + "/json"));
});
gulp.task("cleanMid", function() {
    return gulp.src(tmpPath.build)
        .pipe(clean());
})
gulp.task('csslibtoMid', function() {
    gulp.src(tmpPath.dev + "/css/lib/**")
        .pipe(gulp.dest(tmpPath.mid + "/css/lib/"));
});
//
//替换被编译的less尾缀
gulp.task('remove', function() {
    gulp.src(tmpPath.dev + "/template.html")
        .pipe(replace('.less">', '.css">'))
        .pipe(gulp.dest('build/'));
})

//生产环境------------------
//图片、css、加MD5
gulp.task('imgtoDist', function() {
    var imgSrc = tmpPath.mid + '/images/**',
        quoteSrc = [tmpPath.mid + '/css/**/*.css', tmpPath.mid + '/**/*.html'], // [./output/static/css/**/*.css',./output/static/js/**/*.js'] 
        imgDst = tmpPath.build + '/images';

    return gulp.src(imgSrc)
        //.pipe(gwatch(imgSrc))
        .pipe(md5(10, quoteSrc))
        .pipe(gulp.dest(imgDst));
});
gulp.task('csstoDist', function() {
    var imgSrc = tmpPath.mid + '/css/**', //修改名字的[文件]
        quoteSrc = tmpPath.mid + '/**/*.html', //修改的引入文件的html
        imgDst = tmpPath.build + '/css/' //修改名字后的[文件]输出

    return gulp.src(imgSrc)
        //  .pipe(gwatch(imgSrc))
        .pipe(md5(5, quoteSrc))
        .pipe(gulp.dest(imgDst));
});

gulp.task('htmltoDist', function() {
    gulp.src(tmpPath.mid + "/**/*.html")
        .pipe(gulp.dest(tmpPath.build + "/"));
});
gulp.task("cleanDist", function() {
    return gulp.src(tmpPath.build)
        .pipe(clean());
})
gulp.task('jstoDist', function() {
    gulp.src(tmpPath.mid + "/js/**/*")
        .pipe(gulp.dest(tmpPath.build + "/js"));
});

//定义删除文件适合同步mid目录
var deleSyncMid = function(event, fn) {
    var distFile = tmpPath.mid + "/" + path.relative("./src", event.path); //计算相对路径
    if (event.type == "deleted") {
        fileSystem.existsSync(distFile) && fileSystem.unlink(distFile);
    } else {
        if (typeof fn == "function") { fn() }
    }
}

gulp.task('watch', ['browser'], function() {
    var formatDevPath = tmpPath.dev.substring(2);
    //监听less
    gulp.watch(formatDevPath + '/css/**/*.less', function(event) {
        runSequence("less");

    });
    // //监听html和html模板
    gulp.watch(formatDevPath + '/*.html', function(event) {
        deleSyncMid(event, function() {
            runSequence("import");
        });
    });
    gulp.watch(formatDevPath + '/component/**/*.html', ['import']);
    //图片操作
    gulp.watch(formatDevPath + '/images/**/*', function(event) {
        deleSyncMid(event, function() {
            runSequence("image");
        });
    });
    //js操作
    gulp.watch(formatDevPath + '/js/**', function(event) {
        deleSyncMid(event, function() {
            runSequence("js");
        });
    });
});

//开发环境入口
gulp.task('dev', function() {
    runSequence("cleanMid", "csslibtoMid", "less", "import", "js", "image", "json", 'watch');
});
//生产环境入口
// gulp.task('prevDev', function() {
//     runSequence("cleanMid", "csslibtoMid", "less", "import", "js", "image", "json");
// });
gulp.task('build', function() {
    runSequence("cleanDist", "imgtoDist", "csstoDist", "jstoDist", "htmltoDist");
});

var TOOL = {
    /*
        dir:将要被清理的目录
    */
    clearDir: function(Dir) {
        return gulp.src(Dir)
            .pipe(clean());
    },
    /*
        fdir {string} 将要被移动的目录
        tdir  {string} 移动的目标目录
    */
    mvFile: function(opt) {
        gulp.src(opt.fdir)
            .pipe(gulp.dest(opt.tdir));
    },
    /*
       html:{string} 需要执行import的html
       component：{string} import组件的目录
       tDir {string} import后输出到指定目录
     */
    importHtml: function(opt) {
        // gulp.src(opt.html)
        return gwatch(opt.html)
            .pipe(gwatch(opt.component))
            .pipe(fileinclude({
                prefix: '@@',
                basepath: opt.component
            }))
            .pipe(gulp.dest(opt.tDir))
            .pipe(notify({
                message: "import html: <%= file.relative %>"
            }))
            .pipe(reload({ stream: true }));
    },
    /*
     file {string} 被修改的文件，例如：tmpPath.mid+'/css/**',//修改名字的[文件]
      quoteSrc {Array or string} 需要用到被修改文件的file，替换他们的路径
      distDir {string}  file加MD5后输出到指定目录
    */
    fileMd5: function(opt) {
        //return gulp.src(opt.file)
        return gwatch(opt.file)
            .pipe(md5(10, opt.quoteSrc))
            .pipe(gulp.dest(opt.distDir));
    },
    /*
        dir {string} 要被替换的文件
        target {string} 要被替换的文本
        $1 {string} 替换的文本
        tDir {string} 要输出的目录
    */
    fileContentReplace: function(opt) {
        return gulp.src(opt.dir)
            .pipe(replace(opt.target, opt.$1))
            .pipe(gulp.dest(opt.tDir));
    },
    /*
        event:事件
        fn：回调函数
        removePath:{string} 被同步的path
        releasePath:{string} 当前的path
    */
    syncDeleorAddfile: function(opt) {
        var distFile = removePath + "/" + path.relative(opt.releasePath, opt.event.path); //计算相对路径,opt.releasePath=>./src
        if (event.type == "deleted") {
            fileSystem.existsSync(distFile) && fileSystem.unlink(distFile);
        } else {
            if (typeof opt.fn == "function") { opt.fn() }
        }
    },
    /*
        targetPath:{string}目标路径-》tmpPath.cssDev+'\/**\/*\.less
        toPath:{string} 输出的路径，不包括文件名
    */
    compileLess: function(opt) {
        return gulp.src(targetPath)
            // `changed` 任务需要提前知道目标目录位置
            // 才能找出哪些文件是被修改过的
            .pipe(sourcemaps.init())
            .pipe(less())
            .pipe(autoprefixer('last 10 version'))
            .pipe(px2rem(px2remOptions))
            .pipe(concat("index.css")) //合并到一个文件
            .pipe(sourcemaps.write(opt.toPath + "/css/maps"))
            .pipe(gulp.dest(opt.toPath + "/css"))
            .pipe(notify({
                message: "Generated file: <%= file.relative %>"
            }))
            .pipe(reload({ stream: true }));
    }



};
